﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlServerCe;
using System.Collections;

namespace RCSnake
	{
	/// <summary>
	/// 
	/// </summary>
	public partial class FormResults : Form
		{
		/*---------------------------------------------*\
		|*                 Attributs                   *|
		\*---------------------------------------------*/
		private int m_result;
		private int m_length;

		/*---------------------------------------------*\
		|*                Constructeur                 *|
		\*---------------------------------------------*/
		/// <summary>
		/// 
		/// </summary>
		/// <param name="result"></param>
		/// <param name="length"></param>
		public FormResults(int result, int length)
			{
			InitializeComponent();
			m_result = result;
			m_length = length;
			this.btnOk.Enabled = false;
			}

		/*---------------------------------------------*\
		|*              Methodes private               *|
		\*---------------------------------------------*/
		private int getBestScore(SqlCeConnection connection)
            {
            String query = "select top(1) * from Score order by Score.points desc";
      
            SqlCeCommand cmd = new SqlCeCommand();
            cmd.Connection = connection;
            cmd.CommandText = query;

            DataSet ds = new DataSet();
            SqlCeDataAdapter da = new SqlCeDataAdapter(cmd);
            da.Fill(ds, "Score");

            DataTable table = ds.Tables["Score"];

            IEnumerator en = table.Rows.GetEnumerator();
            en.Reset();
            en.MoveNext();

            return Convert.ToInt32(((DataRow)en.Current)["points"]);
            }

        private int getSmallestScore(SqlCeConnection connection)
            {
            String query = "select top(1) * from Score order by Score.points asc";

            SqlCeCommand cmd = new SqlCeCommand();
            cmd.Connection = connection;
            cmd.CommandText = query;

            DataSet ds = new DataSet();
            SqlCeDataAdapter da = new SqlCeDataAdapter(cmd);
            da.Fill(ds, "Score");

            DataTable table = ds.Tables["Score"];

            IEnumerator en = table.Rows.GetEnumerator();
            en.Reset();
            en.MoveNext();

            return Convert.ToInt32(((DataRow)en.Current)["points"]);
            }

        private void removeSmallestScore(SqlCeConnection connection)
            {
            String query = "select top(1) * from Score order by Score.points ASC, Score.length DESC, Score.name ASC";

            SqlCeCommand cmd = new SqlCeCommand();
            cmd.Connection = connection;
            cmd.CommandText = query;

            DataSet ds = new DataSet();
            SqlCeDataAdapter da = new SqlCeDataAdapter(cmd);
            da.Fill(ds, "Score");

            DataTable table = ds.Tables["Score"];

            table.Rows.Remove(table.Rows[0]);
            SqlCeCommandBuilder bldr = new SqlCeCommandBuilder(da);
            da.Update(table);
            }

        private void insertScore(SqlCeConnection connection)
            {
            String query = "select * from Score";

            SqlCeCommand cmd = new SqlCeCommand();
            cmd.Connection = connection;
            cmd.CommandText = query;

            DataSet ds = new DataSet();
            SqlCeDataAdapter da = new SqlCeDataAdapter(cmd);
            da.Fill(ds, "Score");

            DataTable table = ds.Tables["Score"];

            DataRow newLine = table.NewRow();

            newLine["name"] = this.txtName.Text;
            newLine["points"] = m_result;
            newLine["length"] = m_length;

            ds.Tables["Score"].Rows.Add(newLine);
            SqlCeCommandBuilder bldr = new SqlCeCommandBuilder(da);
            da.Update(table);
            }

        private void addScore()
            {
            SqlCeConnectionSecure sqlConnection = new SqlCeConnectionSecure(Parameters.DEFAULT_DATABASE_NAME);
            try
                {
				if(Tools.getNbLines(sqlConnection.connection, "Score") < Parameters.DEFAULT_NB_SCORE)
                    {
                    this.insertScore(sqlConnection.connection);
                    }
                else if (m_result > this.getSmallestScore(sqlConnection.connection))
                    {
                    this.removeSmallestScore(sqlConnection.connection);
                    this.insertScore(sqlConnection.connection);
                    }
                }
            catch (Exception e)
                {
                MessageBox.Show(e.ToString(), "SQL insert error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }

        private void btnOk_Click(object sender, EventArgs e)
            {
            this.addScore();
            this.Close();
            }

        private void btnCancel_Click(object sender, EventArgs e)
            {
            this.Close();
            }

        private void txtName_TextChanged(object sender, EventArgs e)
            {
            if (this.txtName.Text.Length <= 0)
                {
                this.btnOk.Enabled = false;
                }
            else
                {
                this.btnOk.Enabled = true;
                }
            }
		}
	}
